﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Configuration;
using DaCredito;
using DA_OOMModel;
using DA_OOMNHibernateDAL;
using DA_OOMModelIDAL;
using DA_OOMDALFactory;

namespace DaCredito
{
    public class Global : System.Web.HttpApplication
    {
        public static Global Instance
        {
            get { return (Global)HttpContext.Current.ApplicationInstance; }
        }

        public static string LoginUrl
        {
            get
            {
                AuthenticationSection authenticationSection = (AuthenticationSection)WebConfigurationManager.GetSection(
                  "system.web/authentication");
                return ((FormsAuthenticationConfiguration)authenticationSection.ElementInformation.Properties["forms"].Value).LoginUrl;
            }
        }


        /// <summary>
        /// Chama OnUserLoggedOut e destrói a sessão que estiver ativa.
        /// </summary>
        public void UserLoggedOut()
        {
            this.OnUserLoggedOut();
            try { this.Session.Abandon(); }
            catch { /* Nothing to do */ }
        }

        public static WebSettings Settings
        {
            get { return WebSettings.Global; }
        }

        protected virtual void OnStart()
        {
           

        }

        protected virtual void OnEnd()
        {
        }

        protected virtual void OnSessionStart()
        {
            IUsuarioDAL loUsuarioDAO = ConcreteDALFactory.CreateUsuarioDAL();
            Usuario loUsuario = loUsuarioDAO.Load(new UsuarioPK(1));
            Session["Usuario"] = loUsuario;
            Session["Cliente"] = loUsuario.Cliente;
        }

        protected virtual void OnSessionEnd()
        {
        }

        protected virtual void OnError(Exception aoError)
        {
        }

        protected virtual void OnPreRequestHandlerExecute()
        {
        }

        protected virtual void OnPostRequestHandlerExecute()
        {
        }

        protected virtual void OnUserLoggedOut()
        {
        }

        protected virtual void OnBeginRequest()
        {
        }

        protected virtual void OnEndRequest()
        {
        }
        protected bool IsSessionAvailable
        {
            get { return HttpContext.Current.Session != null; }
        }

        #region Global Events

        /// <summary>
        /// Carrega as configurações de Settings da aplicação a partir de Web.config.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Start(Object sender, EventArgs e)
        {
            // Configura o log através do arquivo .config da aplicação
            //log4net.Config.XmlConfigurator.Configure();
            //Logger.Log(this).Info("Log started.");
            // Configura o objeto Settings
            WebSettings.Global = new WebSettings();
            //log4net.Config.XmlConfigurator.Configure();
            //Logger.Log(this).DebugFormat("Settings: {0}", Settings.Items.ToString(Environment.NewLine));
            this.OnStart();
        }

        protected void Application_End(Object sender, EventArgs e)
        {
            this.OnEnd();
        }

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            this.OnBeginRequest();
        }

        protected void Application_EndRequest(Object sender, EventArgs e)
        {
            this.OnEndRequest();
        }

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
        }

        protected void Application_Error(Object sender, EventArgs e)
        {
            try
            {
                Exception loError = HttpContext.Current.Server.GetLastError();
                loError = TFCException.GetRootException(loError);
                if (!(loError is AbortException))
                {
                   
                      //  if (!loError.ToString().StartsWith("System.Web.HttpException: File does not exist"))
                          //  Logger.Log(this).Error("Error: " + loError.Message, loError);
                    
                }
                this.OnError(loError);
            }
            catch (Exception ex)
            {
                // Evita a propagação de erros
                System.Diagnostics.Debug.WriteLine("Error: " + ex);
            }
        }

        protected void Application_AcquireRequestState(Object sender, EventArgs e)
        {
        }

        protected void Application_PostAcquireRequestState(Object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Abre a conexão com o banco antes de chamar OnPreRequestHandlerExecute.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
        {
            this.OnPreRequestHandlerExecute();
        }

        /// <summary>
        /// Termina a conexão com o banco após chamar OnPostRequestHandlerExecute.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_PostRequestHandlerExecute(Object sender, EventArgs e)
        {
            this.OnPostRequestHandlerExecute();
        }

        protected void Application_ReleaseRequestState(Object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Cria o objeto de conexão e o armazena na sessão.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Session_Start(Object sender, EventArgs e)
        {
            this.OnSessionStart();
        }

        /// <summary>
        /// Chama o método OnSessionEnd.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Session_End(Object sender, EventArgs e)
        {
            this.OnSessionEnd();
        }

        #endregion


    }
}
